package cn.jingyuan.swan.uaa.web.config;

import cn.jingyuan.swan.cloud.web.DefaultWebMvcConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;

import java.io.IOException;
import java.util.List;


@Configuration
public class WebMvcConfiguration extends DefaultWebMvcConfiguration {

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        AccessTokenConverter accessTokenConverter = new AccessTokenConverter();
        converters.add(0, accessTokenConverter);
    }

    /**
     * FastJson 序列化 AccessToken 会有问题，故特殊处理
     */
    public class AccessTokenConverter extends AbstractHttpMessageConverter<OAuth2AccessToken> {

        private final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();

        public AccessTokenConverter() {
            super(MediaType.APPLICATION_JSON);
        }

        @Override
        protected boolean supports(Class<?> clazz) {
            return clazz.equals(DefaultOAuth2AccessToken.class);
        }

        @Override
        protected DefaultOAuth2AccessToken readInternal(Class<? extends OAuth2AccessToken> clazz, HttpInputMessage inputMessage)
            throws IOException, HttpMessageNotReadableException {
            throw new UnsupportedOperationException("This converter is only used for converting OAuth2AccessToken to json");
        }

        @Override
        protected void writeInternal(OAuth2AccessToken accessToken, HttpOutputMessage outputMessage)
            throws IOException, HttpMessageNotWritableException {
            converter.write(accessToken, MediaType.APPLICATION_JSON, outputMessage);
        }

    }

}
